package com.amtf.datafile3.core.fil;

import java.io.File;
import java.util.List;

import com.amtf.common.Util;
import com.amtf.datafile3.DataException;
import com.amtf.datafile3.DataTable;
import com.amtf.datafile3.DataTableDefinition;
import com.amtf.datafile3.cfg.fil.FilDataDefinitionFactory;
import com.amtf.datafile3.core.std.AbsDataCatalog;

public class FilDataCatalog extends AbsDataCatalog {
	private File dir = null;
	private String charset = "UTF-8";
	private int startRow = 1;
	private boolean firstRowTitle;

	public FilDataCatalog(String name, File dirOrFile, String filePattern, boolean subFolder, String charset, int startRow, boolean firstRowTitle, int[] columnsLength)
			throws DataException {
		super(name);
		this.charset = charset;
		this.startRow = startRow;
		this.firstRowTitle = firstRowTitle;

		DataTableDefinition dtd = FilDataDefinitionFactory.create(name, charset, startRow, firstRowTitle, columnsLength);
		if (!dirOrFile.exists() || dirOrFile.isFile()) {
			this.dir = dirOrFile.getParentFile();

			FilDataTable dt = new FilDataTable(dirOrFile.getName(), dtd, dirOrFile, charset, startRow, firstRowTitle);
			setDataTable(dt.getName(), dt);
		} else if (dirOrFile.isDirectory()) {
			this.dir = dirOrFile;

			List<File> files = Util.fsFindFiles(dirOrFile.getPath(), filePattern, subFolder);
			for (File file : files) {
				FilDataTable dt = new FilDataTable(file.getName(), dtd.clone(), file, charset, startRow, firstRowTitle);
				setDataTable(dt.getName(), dt);
			}
		}
	}

	public DataTable createDataTable(String name, DataTableDefinition definition) throws DataException {
		if (this.isDataTableExists(name) && getDataTableFile(name).length() != 0) {
			throw new DataException("Data table exist!");
		}

		FilDataTable dt = new FilDataTable(name, definition, getDataTableFile(name), charset, startRow, firstRowTitle);

		setDataTable(dt.getName(), dt);
		return dt;
	}

	@Override
	public DataTable dropDataTable(String name) throws DataException {
		DataTable dt = getDataTable(name);
		if (dt != null) {
			dt.close();
			boolean deled = getDataTableFile(name).delete();
			if (!deled) {
				throw new DataException("Failed to drop " + name);
			}
		}

		return super.dropDataTable(name);
	}

	private File getDataTableFile(String name) {
		String newfile = dir.getPath() + File.separator + name;
		return new File(newfile);
	}
}
